package com.cie2.janji.pages.users;

import java.io.File;
import java.util.Date;

import org.apache.commons.fileupload.FileUploadException;
import org.apache.tapestry5.PersistenceConstants;
import org.apache.tapestry5.annotations.Component;
import org.apache.tapestry5.annotations.Persist;
import org.apache.tapestry5.annotations.Property;
import org.apache.tapestry5.hibernate.annotations.CommitAfter;
import org.apache.tapestry5.ioc.annotations.Inject;
import org.apache.tapestry5.services.ApplicationGlobals;
import org.apache.tapestry5.upload.services.UploadedFile;
import org.chenillekit.tapestry.core.components.Editor;

import com.cie2.janji.base.CieUserPage;
import com.cie2.janji.entities.Article;
import com.cie2.janji.entities.User;
import com.cie2.janji.services.ArticleService;

public class CreateArticle extends CieUserPage {

	@Property
	private Article article;
	
	@Property
	private Long articleId;

	@Component(parameters = {"value=editor1Value"})
	private Editor editor1;

	@Component(parameters = {"value=editor2Value"})
	private Editor editor2;
	
	@Property
	private String editor1Value;

	@Property
	private String editor2Value;
	
	// for uploaded file
	@Property
	private UploadedFile file;

	@Inject
	private ApplicationGlobals applicationGlobals;
	
	//services
	@Inject
	private ArticleService articleService;
	
	@CommitAfter
	Object onSuccess() {
		
		if(null == articleId)
			addArticle();		
		else
			updateArticle();
		
		return ArticleList.class;
	}

	/**
	 * 
	 */
	private void addArticle() {
		if(file != null) {
			
			String realPath = applicationGlobals.getServletContext().getRealPath("/");
			
			String filename = "A_" + file.getFileName();
			File copied = new File(realPath + File.separatorChar +"images" + File.separatorChar  
					+ "article" + File.separatorChar + filename);
	
			file.write(copied);

			article.setImage(filename);
		}  		
		
		User currentUser = getVisit().getUser();
		article.setAuthor(currentUser);
		article.setAbstraction(editor1Value);
		article.setContent(editor2Value);
		
		article.setCreatedDate(new Date());
		articleService.add(article);
	}
	
	private void updateArticle() {
		article.setAbstraction(editor1Value);
		article.setContent(editor2Value);
		article.setUpdatedDate(new Date());
		articleService.add(article);
	}
	
	// error handling for upload file
	@Persist(PersistenceConstants.FLASH)
	@Property
	private String message;

	Object onUploadException(FileUploadException ex) {
		message = "Upload exception: " + ex.getMessage();

		return this;
	}
	
	Long onPassivate() {
		return articleId;
	}

	void onActivate(Long articleId) {
		this.articleId = articleId;
		article = articleService.load(articleId);

		editor1Value = article.getAbstraction();
		editor2Value = article.getContent();
	}
}
